<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./canvas.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
  <img id="img01" src="./bg3.png" alt="" />
  <h2>canvas</h2>
  <hr/>
  <div>
    <canvas id="canvas01" width="750" height="168"></canvas>
    <canvas id="canvas02" width="750" height="227"></canvas>
  </div>
  <h2>upload Image</h2>
  <hr/>
  <div>
    <img id="d01" />
    <img id="d02" />
  </div>

  <script>
    // 这里使用canvas切割图片，切割为750x168、750x227大小，并上传
    let img01 = document.getElementById('img01')
    img01.onload = (e) => {
      let c01 = document.getElementById('canvas01')
      let c02 = document.getElementById('canvas02')
      let ctx01 = c01.getContext('2d')
      let ctx02 = c02.getContext('2d')
      let iw = img01.clientWidth
      let ih = img01.clientHeight
      let a1 = Math.floor(iw * 168 / 750)
      let a2 = Math.floor(iw * 227 / 750)
      // 图片切割
      ctx01.drawImage(img01, 0, 0, iw, a1, 0, 0, 750, 168)
      ctx02.drawImage(img01, 0, a1 + 1, iw, a2, 0, 0, 750, 227)
      let url01 = c01.toDataURL()
      let url02 = c02.toDataURL()
      let d01 = document.getElementById('d01')
      // d01.src = url01
      let d02 = document.getElementById('d02')
      // d02.src = url02
      let b01 = dataURLToBlob(url01)
      let b02 = dataURLToBlob(url02)

      const file01 = new File([b01], 'img01.png', {type: 'image/png'})
      const newFormData01 = new FormData()
      newFormData01.append('file', file01)
      axios({
        method: 'POST',
        url: 'http://website.com/file/upload',
        data: newFormData01,
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: "Bearer c5016461-28f1-405b-8bd5-674bbfb6873b"
        }
      }).then(res => {
        console.log('res01', res)
        d01.src = res.data.data[0]
      }).catch(err => {
        console.log(err)
      })

      const file02 = new File([b02], 'img02.png', {type: 'image/png'})
      const newFormData02 = new FormData()
      newFormData02.append('file', file02)
      axios({
        method: 'POST',
        url: 'http://website.com/file/upload,
        data: newFormData02,
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: "Bearer c5016461-28f1-405b-8bd5-674bbfb6873b"
        }
      }).then(res => {
        console.log('res02', res)
        d02.src = res.data.data[0]
      }).catch(err => {
        console.log(err)
      })
    }
    
  </script>
</body>
</html>